// 引入flutter包
import 'dart:math';

import 'package:flutter/material.dart';

// 引入flutter的material包 LoginPage 继承自 StatelessWidget 管理状态
class LoginPage extends StatelessWidget {
  final Function(Map<String, dynamic>) onLoginSuccess;

  const LoginPage({super.key, required this.onLoginSuccess});


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false, // 不显示右上角的 debug
        title: '好睡',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        // 注册路由表
        routes: {
          "/": (context) => LoginBox(
            title: "登录",
            onLoginSuccess: onLoginSuccess, // 添加此行
          ),});
  }
}

class LoginBox extends StatefulWidget {
  const LoginBox({Key? key, required this.title, required this.onLoginSuccess}) : super(key: key);
  final String title;
  final Function(Map<String, dynamic>) onLoginSuccess;

  @override
  _LoginBoxState createState() => _LoginBoxState();
}


class _LoginBoxState extends State<LoginBox> {
  final GlobalKey _formKey = GlobalKey<FormState>();
  late String _email, _password;
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;
  final List _loginMethod = [
    {
      "title": "tiktok",
      "icon": Icons.tiktok,
    },
    {
      "title": "google",
      "color": Colors.red,
      "icon": Icons.fiber_dvr,
    },
    {
      "title": "twitter",
      "icon": Icons.account_balance,
    },
  ];
  late TextEditingController _emailController;
  late TextEditingController _passwordController;

  @override
  void initState() {
    super.initState();
    _email = '123123@qq.com'; // 设置默认值为空字符串
    _password = '123123'; // 设置默认值为空字符串
    _emailController = TextEditingController(text: _email);
    _passwordController = TextEditingController(text: _password);
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xff0b0b33),
      body: Form(
        key: _formKey, // 设置globalKey，用于后面获取FormStat
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          children: [
            const SizedBox(height: kToolbarHeight), // 距离顶部一个工具栏的高度
            buildTitle(), // Login
            buildTitleLine(), // Login下面的下划线
            // const SizedBox(height: 60),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.cloud,
                  size: 130,
                  color: Colors.grey[200],
                ),
                const Text(
                  '好睡 你的好睡眠123',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Color(0xffeeeeee),
                  ),
                ),
              ],
            ),
            buildEmailTextField(), // 输入邮箱
            const SizedBox(height: 30),
            buildPasswordTextField(context), // 输入密码
            buildForgetPasswordText(context), // 忘记密码
            const SizedBox(height: 60),
            buildLoginButton(context), // 登录按钮
            const SizedBox(height: 40),
            buildOtherLoginText(), // 其他账号登录
            buildOtherMethod(context), // 其他登录方式
            buildRegisterText(context), // 注册
          ],
        ),
      ),
    );
  }

  Widget buildRegisterText(context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.only(top: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('没有账号?',style: TextStyle(color: Color(0xffeeeeee)),),
            GestureDetector(
              child: const Text('点击注册', style: TextStyle(color: Color(
                  0xff13abff))),
              onTap: () {
                print("点击注册");
              },
            )
          ],
        ),
      ),
    );
  }

  Widget buildOtherMethod(context) {
    return ButtonBar(
      alignment: MainAxisAlignment.center,
      children: _loginMethod
          .map((item) => Builder(builder: (context) {
                return IconButton(
                    icon: Icon(item['icon'],
                        color: Colors.white),
                    onPressed: () {
                      //TODO: 第三方登录方法
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                            content: Text('${item['title']}登录'),
                            action: SnackBarAction(
                              label: '取消',
                              onPressed: () {},
                            )),
                      );
                    });
              }))
          .toList(),
    );
  }

  Widget buildOtherLoginText() {
    return const Center(
      child: Text(
        '其他账号登录',
        style: TextStyle(color: Colors.grey, fontSize: 14),
      ),
    );
  }

  Widget buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45,
        width: 270,
        child: ElevatedButton(
          style: ButtonStyle(
            // 设置圆角
            shape: MaterialStateProperty.all(const StadiumBorder(
              side: BorderSide(style: BorderStyle.none),
            )),
            // foregroundColor: MaterialStateProperty.all(Colors.black),
          ),
          child: Text('登陆',
              style: Theme.of(context)
                  .primaryTextTheme
                  .headlineSmall
                  ?.copyWith(color: Colors.black)),
          onPressed: () {
            // 表单校验通过才会继续执行
            if ((_formKey.currentState as FormState).validate()) {
              (_formKey.currentState as FormState).save();
              //TODO 执行登录方法
              // 导航到 home_page.dart
              // 这是登录成功后的逻辑
              final Map<String, dynamic> args = {
                'email':  _email,
                'password': _password
              };
              widget.onLoginSuccess(args);
              // print('email: $_email, password: $_password');
            }
          },
        ),
      ),
    );
  }

  Widget buildForgetPasswordText(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Align(
        alignment: Alignment.centerRight,
        child: TextButton(
          onPressed: () {
            // Navigator.pop(context);
            print("忘记密码");
          },
          child: const Text("忘记密码？",
              style: TextStyle(fontSize: 14, color: Colors.white)),
        ),
      ),
    );
  }

  Widget buildPasswordTextField(BuildContext context) {

    return TextFormField(
        controller: _passwordController, // 使用控制器
      style: const TextStyle(color: Colors.white),
        obscureText: _isObscure, // 是否显示文字
        onSaved: (v) => _password = v!,
        validator: (v) {
          if (v!.isEmpty) {
            return '请输入密码';
          }
        },
        decoration: InputDecoration(
            labelText: "密码",
            labelStyle: const TextStyle(color: Colors.white),
            errorStyle: const TextStyle(color: Color(0xffff4b4b)),
            suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor,
              ),
              onPressed: () {
                // 修改 state 内部变量, 且需要界面内容更新, 需要使用 setState()
                setState(() {
                  _isObscure = !_isObscure;
                  _eyeColor = (_isObscure
                      ? Colors.red
                      : Theme.of(context).iconTheme.color)!;
                });
              },
            )));
  }

  Widget buildEmailTextField() {
    return TextFormField(
      controller:  _emailController,
      style: const TextStyle(color: Colors.white),
      decoration: const InputDecoration(
          labelText: '邮箱地址',
          labelStyle: TextStyle(color: Colors.white),
          errorStyle: TextStyle(color: Color(0xffff4b4b))),
      validator: (v) {
        var emailReg = RegExp(
            r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
        if (!emailReg.hasMatch(v!)) {
          return '请输入正确的邮箱地址';
        }
      },
      onSaved: (v) => _email = v!,
    );
  }

  Widget buildTitleLine() {
    return Padding(
        padding: const EdgeInsets.only(left: 12.0, top: 4.0),
        child: Align(
          alignment: Alignment.bottomLeft,
          child: Container(
            color: Colors.white,
            width: 40,
            height: 2,
          ),
        ));
  }

  Widget buildTitle() {
    return const Padding(
        padding: EdgeInsets.all(8),
        child: Text(
          '登陆',
          style: TextStyle(fontSize: 42, color: Colors.white),
        ));
  }
}
